package com.hgc.consumerrabbit.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

/**
 *  RabbitMQ配置类
 *  如果交换机和队列不存在会自动创建
 */

@Component
public class RabbitMQConfig {
    // 交换机名字(空为使用默认的交换机)
    private String EXCHANGES_NAME = "EXCHANGES_DEMO";

    // 队列名字
    private String SMS_QUEUE = "QUEUE_DEMO";
    private String EMAIL_QUEUE = "QUEUE_EMAIL";

    // 注入交换机到spring容器中
    @Bean
    public FanoutExchange fanoutExchange(){
        return new FanoutExchange(EXCHANGES_NAME);
    }

    // 注入队列
    @Bean
    public Queue smsQueue(){
        return new Queue(SMS_QUEUE);
    }
    @Bean
    public Queue emailQueue(){
        return new Queue(EMAIL_QUEUE);
    }

    // 关联交换机
    @Bean
    public Binding binding1(Queue smsQueue,FanoutExchange fanoutExchange){
        return BindingBuilder.bind(smsQueue).to(fanoutExchange);
    }
    @Bean
    public Binding binding2(Queue emailQueue,FanoutExchange fanoutExchange){
        return BindingBuilder.bind(emailQueue).to(fanoutExchange);
    }


    /**
     * 消费者JSON序列化
     */
    @Bean
    public MessageConverter jsonMessageConverter(ObjectMapper objectMapper) {
        return new Jackson2JsonMessageConverter(objectMapper);
    }
}
